package com.zhuangjie.shop.handler.activity.handler.impl;

import com.zhuangjie.shop.entity.ShopActivityInstance;
import com.zhuangjie.shop.enums.ActivityType;
import com.zhuangjie.shop.enums.BusinessTypeEnum;
import com.zhuangjie.shop.handler.activity.ActivityEnv;
import com.zhuangjie.shop.handler.activity.handler.ActivityHandler;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 配送费活动处理程序
 *
 * @author zhuangjie
 * @date 2024/06/14
 */
public class DeliveryFeeActivityHandler  extends ActivityHandler {

    /**
     * 配送费等级分隔符
     */
    private static final String FULL_REDUCTION_SEPARATOR = ",";

    @Override
    public ActivityType activityType() {
        return ActivityType.DELIVERY_FEE_DISCOUNT;
    }

    @Override
    public void checkActivityValid(ShopActivityInstance shopActivityInstance) {

    }

    @Override
    public BigDecimal calculateDiscountsHandler(ActivityEnv env, ShopActivityInstance shopActivityInstance) {
        // 如果不是配送单，则配送活动不可用
        if (!Objects.equals(env.getMetaInformation().getReceivingMethod(), BusinessTypeEnum.DELIVERY.getValue())) {
            return null;
        }
        // 1. 准备前置需要的信息
        // 用户的收货地址与店铺的距离
        Double userAddressShopDistance = env.getDistance();
        // 如就是无法计算得到距离，那就先略过的配送活动，提交订单时如果是配送单肯定是会有的
        if (userAddressShopDistance == null) return null;
        // 店铺的配送费（最高可减免的配送金额）
        BigDecimal deliveryFee = env.getShop().getDeliveryFee();

        // 2. 计算满足的满减级别（maxSatisfiedThresholdIndex）
        List<Double> distanceThresholds = Arrays.stream(shopActivityInstance.getThreshold().split(FULL_REDUCTION_SEPARATOR)).map(Double::parseDouble).collect(Collectors.toList());

        int satisfiedThresholdIndex = -1;
        Double satisfiedThreshold = null;

        for (int i = 0; i < distanceThresholds.size(); i++) {

            Double currentThreshold = distanceThresholds.get(i);
            if(currentThreshold.compareTo(userAddressShopDistance) >= 0 && ( satisfiedThreshold == null || currentThreshold < satisfiedThreshold)) {
                satisfiedThreshold = currentThreshold;
                satisfiedThresholdIndex = i;
            }
        }

        // 3. 获取对应的values优惠值返回
        if (satisfiedThresholdIndex == -1) {
            return null;
        }
        List<String> values = Arrays.stream(shopActivityInstance.getValue().split(FULL_REDUCTION_SEPARATOR)).collect(Collectors.toList());
        BigDecimal discountsValue =  new BigDecimal(values.get(satisfiedThresholdIndex));
        return discountsValue.doubleValue() > deliveryFee.doubleValue()? deliveryFee: discountsValue;
    }
}
